//
//  StatusVModelList.swift
//  新浪微博01
//
//  Created by 李国伟 on 15/12/11.
//  Copyright © 2015年 李国伟. All rights reserved.
//

import Foundation
import SDWebImage
/// 封装网络方法，下载数据
class StatusVModelList{
    
    //设置模型数组
    lazy var statusVModelList = [AnyObject]()
    
    //下拉刷新条数
    var refreshCount: Int?

    //通过数据库管理类加载数据，有诸多bug，仅为了增加此功能。
    func loadDates(ispullup ispullup:Bool,fished: (isSuccess: Bool) -> ()){
        
        //设置上拉和下拉参数
        let viewModel = statusVModelList.first as? StatusViewModel
        let since_id = ispullup ? 0 :(viewModel?.status.id ?? 0)
        let max_id = ispullup ? ((statusVModelList.last as! StatusViewModel).status.id - 1) ?? 0 : 0

        StatusDAL.loadStatus(since_id, max_id: max_id) { (array) -> () in
            
            //做容错处理防止，从数据库加载的数据为空
            guard let arrD = array else{
                fished(isSuccess: false)
                return
            }
            //创建一个可变数组存储模型
            var dateList = [AnyObject]()
            
            //遍历数组进行字典转模型
            for dic in arrD {
                
                let vm = StatusViewModel(status: Status(dict: dic))
                dateList.append(vm)
                
            }
            
            //下拉刷新数量
            self.refreshCount = dateList.count > 0 ? dateList.count : nil
            
            //拼接模型
            if !ispullup {
                self.statusVModelList = dateList + self.statusVModelList
            } else{
                self.statusVModelList += dateList
            }
            
            self.cahceSingleImage(dateList, finshed: fished)
        }
    }
    
    
    //缓存单张图片
    private func cahceSingleImage(datelist: [AnyObject],finshed: (isSuccess: Bool) -> ()){
        
        //设置一个调度组
        let group = dispatch_group_create()
        
        //统计缓存长度
        var dataLength = 0
        
        //判断是否是单张图片，不是跳过
        for viewMode  in datelist {
            
         let vc = viewMode as? StatusViewModel
            
            //判断是否是单张图片
            if vc?.thumbnailUrls?.count != 1 {
                continue
            }
            
            let url = vc?.thumbnailUrls![0]
                //下面执行的闭包将在调度组内执行
                dispatch_group_enter(group)
            
            SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (image, _, _, _, _) -> Void in
                if let img = image,
                    let data = UIImagePNGRepresentation(img){
                    dataLength += data.length
                }
                
                dispatch_group_leave(group)
             })
           }
        
        //缓存的数据长度
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            
//          let cachelength = dataLength / 1024
//           print("\(cachelength)K")
           finshed(isSuccess: true)
        }
    }
}